/*
 * @Descripttion:
 * @LastEditors: xzh
 * @LastEditTime: 2024-05-10 23:43:43
 */
import axios from "axios";
import { ElNotification } from "element-plus";
import Dile_Methods from "./methods";
import Cookies_Token from "./cache/cookies/token";
import Dile_StoreAction from "./cache/store";
import i18n from "@/international/i18n";

const service = axios.create({
  baseURL: Dile_Methods.getBaseUrl(),
  timeout: 60000,
});

// Request interceptors
service.interceptors.request.use(
  (config: any) => {
    let token = new Cookies_Token().get(),
      //获取当前工厂
      { id: factoryId } = Dile_StoreAction.getCurrentFactory();
    // if (!!token) {
    Object.assign(config.headers, {
      Authorization: !!token ? `Bearer ${token}` : "",
      OrgId: factoryId, //当前工厂
    });
    // }
    return config;
  },
  (error) => {
    Promise.reject(error);
  }
);

// Response interceptors
service.interceptors.response.use(
  (response: any) => {
    // 流文件
    if (response.config["responseType"] === "blob") {
      // 二进制文件流处理
      return response;
    } else {
      // code == 20000: success
      const { code, msg, data } = response.data || {};
      if (code !== 200) {
        ElNotification({
          title: "警告",
          message: msg || "Warning",
          type: "warning",
          duration: 3 * 1000,
        });
        return Promise.reject(new Error(msg || "Error"));
      } else {
        return (data as any) || {};
      }
    }
  },
  (error: any) => {
    let { response, message } = error || {},
      { status, data } = response || {},
      { t } = i18n().global;
    //错误消息
    let errorMessage =
      status == 401 ? t("commom.authExpireToLogin") : data?.msg || message;
    ElNotification({
      title: "错误",
      message: errorMessage,
      type: "error",
      duration: 3 * 1000,
    });
    //登录过期->跳转登录
    status == 401 && Dile_StoreAction.logout();

    return Promise.reject(error);
  }
);

export default service;
